package com.xjc.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author:谢君臣
 * @Date:2021/6/6-9:38
 * @version:1.0
 * @function:
 */
@Aspect
@Component
public class ServiceLog {
    private Logger logger = LoggerFactory.getLogger("Service层日志");

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    //定义切点
    @Pointcut("execution(public * com.xjc.service..*.*(..))")
    public void aopWebLog() {
    }

    //使用@Before在切入点开始处切入内容
    @Before("aopWebLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        System.out.println(startTime.get());
    }

    //使用@AfterReturning在切入点return内容之后切入内容（可以用来对处理返回值做一些加工处理）
    @AfterReturning(pointcut = "aopWebLog()",returning = "retObject")
    public void doAfterReturning(Object retObject) throws Throwable {
        // 处理完请求，返回内容
        logger.info("应答值 : " + retObject);
        logger.info("费时: " + (System.currentTimeMillis() - startTime.get()));
    }

    //使用@AfterThrowing用来处理当切入内容部分抛出异常之后的处理逻辑
    //抛出异常后通知（After throwing advice） ： 在方法抛出异常退出时执行的通知。
    @AfterThrowing(pointcut = "aopWebLog()", throwing = "ex")
    public void addAfterThrowingLogger(JoinPoint joinPoint, Exception ex) {
        logger.error("执行 " + " 异常", ex);
    }

}

